package top.chenziji.Util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;

public class ThumbnailMerger {

    // 合并6张图片成一个缩略图
    public static void createThumbnail(String outputImagePath, String inputDir) throws IOException {
        int width = 1920;  // 每张图片的宽度
        int height = 1080; // 每张图片的高度

        // 创建合并后的缩略图，4行5列，20张图片
        BufferedImage thumbnail = new BufferedImage(width * 5, height * 4, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = thumbnail.createGraphics();

        File[] images = new File(inputDir).listFiles((dir, name) -> name.endsWith(".jpg"));
        if (images == null || images.length < 20) {
            throw new IllegalStateException("There must be at least 20 images to create a thumbnail.");
        }

        // 按行列排列图片，4行5列
        int x = 0, y = 0;
        for (int i = 0; i < 20; i++) {
            BufferedImage img = ImageIO.read(images[i]);
            // 缩放图片到指定尺寸
            BufferedImage scaledImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = scaledImg.createGraphics();
            g.drawImage(img, 0, 0, width, height, null);
            g.dispose();

            // 在合并的图片中绘制缩放后的图片
            g2d.drawImage(scaledImg, x, y, null);

            // 更新坐标，行列布局
            if ((i + 1) % 5 == 0) { // 每5张图片为一行
                x = 0;
                y += height; // 换行
            } else {
                x += width; // 水平增加
            }
        }

        g2d.dispose();
        ImageIO.write(thumbnail, "jpg", new File(outputImagePath));
    }
}

